﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using DigitalRune.Windows.TextEditor;
using EmbeddedSharp.Scripting;
using WeifenLuo.WinFormsUI.Docking;
using Zove.Scripting.Core;
using EmbeddedSharp.Scripting.Function.IO;
using System.Windows.Forms;

namespace Zove.Desktop.Tools {
    public partial class InteractiveWorkBench : DockContent {

        private ZoveScriptingObject intp = null;

        public InteractiveWorkBench() {
            InitializeComponent();

            this.intp = new ZoveScriptingObject();
            this.Load += new EventHandler(InteractiveWorkBench_Load);
            this.tbSource.KeyUp += new KeyEventHandler(tbSource_KeyUp);
        }

        private int offset = 1;

        public void InteractiveWorkBench_Load(object sender, EventArgs e) {
            this.offset = 1;
            this.tbSource.Text = ">";
        }

        private void tbSource_KeyUp(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                int length = this.tbSource.Text.Length;
                string input = this.tbSource.Text.Substring(offset, length - offset);
                string output = Process(input);
                this.tbSource.Text = this.tbSource.Text + "\n\r<" + output + "\n\r>";
                this.offset = this.tbSource.Text.Length;
                this.tbSource.SelectionStart = this.offset;
                this.tbSource.SelectionLength = 0;
            }
        }

        public string Process(string input) {
            if (string.IsNullOrEmpty(input)) {
                return string.Empty;
            }

            try {
                string output = Convert.ToString(
                    this.intp.Process(input));
                return output;
            } catch (ClearScreenException cse) {
                this.tbSource.Text = string.Empty;
            }

            return string.Empty;
        }

        private List<string> history = new List<string>();
    }
}
